package xxx;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Set;

public class NonBlockingClient {

	public static void main(String[] args) throws IOException {
		SocketChannel socketChannel = SocketChannel.open();
		socketChannel.configureBlocking(false);
		Selector selector = Selector.open();
		socketChannel.register(selector, SelectionKey.OP_CONNECT);
		boolean connected = socketChannel.connect(new InetSocketAddress("localhost", 6667));
		while(!connected) {
			int n = selector.select();
			if(n > 0) {
				Set<SelectionKey> selectedKeys = selector.selectedKeys();
				for(SelectionKey key : selectedKeys) {
					if(key.isValid() && key.isConnectable()) {
						selectedKeys.remove(key);
						connected = socketChannel.finishConnect();
					}
				}
			}
		}
		
		socketChannel.register(selector, SelectionKey.OP_WRITE);
		while(true) {
			int n = selector.select();
			if(n > 0) {
				Set<SelectionKey> selectedKeys = selector.selectedKeys();
				for(SelectionKey key : selectedKeys) {
					if(key.isValid() && key.isWritable()) {
						selectedKeys.remove(key);
						
						
						String line = "FOOBAR";
						ByteArrayOutputStream os = new ByteArrayOutputStream();
						DataOutputStream dos = new DataOutputStream(os);
						dos.writeInt(line.length());
						dos.flush();
						Writer w = new OutputStreamWriter(os);
						w.write(line);
						w.flush();
						
						socketChannel.write(ByteBuffer.wrap(os.toByteArray()));

//						DataInputStream dis = new DataInputStream(socket.getInputStream());
//						char[] chars = new char[dis.readInt()];
//						Reader r = new InputStreamReader(socket.getInputStream());
//						r.read(chars);
//						return new String(chars);
					}
				}
			}
		}
		
	}
	
}
